/**
 * Created by liwei.b on 2016/8/5.
 */

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.Iterator;


public class JsonComparer {
    public static void main(String[] args) {
        JSONObject json1 = JSONObject.fromObject("{\n" +
                "\t\"req\": {\n" +
                "\t\t\"Item1\": 171544536,\n" +
                "\t\t\"Item2\": \"1000\",\n" +
                "\t\t\"Item3\": \"203.110.179.201\",\n" +
                "\t\t\"Item4\": 12\n" +
                "\t}\n" +
                "}");
        JSONObject json2 = JSONObject.fromObject("{\n" +
                "\t\"req\": {\n" +
                "\t\t\"Item1\": 171544536,\n" +
                "\t\t\"Item2\": \"1000\",\n" +
                "\t\t\"Item3\": \"203.110.179.201\",\n" +
                "\t\t\"Item4\": 0\n" +
                "\t}\n" +
                "}");
        compareJson(json1, json2, null);

    }

    public static void compareJson(JSONObject json1, JSONObject json2, String key) {
        Iterator<String> i = json1.keys();
        while (i.hasNext()) {
            key = i.next();
            compareJson(json1.get(key), json2.get(key), key);
        }
    }

    public static void compareJson(Object json1, Object json2, String key) {
        if (json1 instanceof JSONObject) {
            compareJson((JSONObject) json1, (JSONObject) json2, key);
        } else if (json1 instanceof JSONArray) {
            compareJson((JSONArray) json1, (JSONArray) json2, key);
        } else if (json1 instanceof String) {
            compareJson((String) json1, (String) json2, key);
        } else {
            compareJson(json1.toString(), json2.toString(), key);
        }
    }

    public static void compareJson(String str1, String str2, String key) {
        if (!str1.equals(str2)) {
            System.out.println("key:" + key + ",json1:" + str1 + ",json2:" + str2);
        }
    }

    public static void compareJson(JSONArray json1, JSONArray json2, String key) {
        Iterator i1 = json1.iterator();
        Iterator i2 = json2.iterator();
        while (i1.hasNext()) {
            compareJson(i1.next(), i2.next(), key);
        }
    }
}